var http = require('http');
var cunto = 80
var fs = require("fs");
var url = require("url")
var querystring = require('querystring');
var ip = "127.0.0.1"
var stieName ='个人日志'
var server = http.createServer(function (request, response) {
	response.statusCode = 200; 
	response.setHeader("Content-Type","text/html");
	var p = url.parse(request.url,true);
	console.log(p)
	var date = '404'
	if (p.pathname == '/index.html') {
		try{
			var date = fs.readFileSync("."+request.url,'utf-8');
				date = date.replace(/%title/g,stieName)
				item = fs.readFileSync('severBack.json','utf-8')
				item = JSON.parse(item);
				var s = ''
		for (var i = 0; i < item.length; i++) {
				s += '<div class="item">'
				s +='<h5>'+item[i].aution+'<span>'+item[i].time+'</span></h5>'
				s +='<p>'+item[i].message+'<a href="/delmessage?id='+i+'">删除</a></p>'
				s +='</div>'
			}
			var date = date.replace(/%s/g,s)
			response.write(date);
			response.end()		
		}catch(e){
			console.log(e)
		}
	}else if (p.pathname == '/form.html') {
		date = fs.readFileSync("."+request.url,'utf-8');
		response.write(date);
		response.end()
	}else if(p.pathname == '/addmessage'){
		/*aution = p.query.aution
		message = p.query.message
		item =JSON.parse(fs.readFileSync('severBack.json','utf-8'));
		//item = JSON.parse(item);//对象用点
		item.push({
			aution:aution,
			message:message,
			time :new Date()
		})
		//item = JSON.parse(fs.readFileSync("."+request.url,'utf-8'));
		item = JSON.stringify(item);
		fs.writeFileSync('severBack.json',item)
		date = '提交成功'
		response.writeHead(302,{
			'Location':'/index.html'
		});*/ 
		 var post = '';     
	 
	    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
	    request.on('data', function(data){    
	        post += data;
	    });
	    // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
	    request.on('end', function(){    
        post = querystring.parse(post);
        // res.end(util.inspect(post));
        item =JSON.parse(fs.readFileSync('severBack.json','utf-8'));
        item.push({
			aution:post.aution,
			message:post.message,
			time :new Date()
		});
		item = JSON.stringify(item);
		fs.writeFileSync('severBack.json',item);
		response.writeHead(302,{
			'Location':'/index.html'
		});
		response.write(date);
		response.end()

    });
	}else if (p.pathname == '/delmessage') {
		id = p.query.id
		item = JSON.parse(fs.readFileSync('severBack.json','utf-8'));
		item.splice(id,1)
		item = JSON.stringify(item);
		fs.writeFileSync('severBack.json',item)
		date = '提交成功'
		response.writeHead(302,{
			'Location':'/index.html'
		});
		response.write(date);
		response.end() 
	}
})
server.listen(cunto);
console.log('Server running at http://%s:%s/',ip,cunto);
